package com.timebank.score.service.impl;

import com.timebank.common.core.exception.ServiceException;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.score.mapper.ScoreTaskTypeMapper;
import com.timebank.score.pojo.entity.ScoreTaskType;
import com.timebank.score.service.ScoreTaskTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 积分任务类型 实现类
 * @author shiliuyinzhen
 */
@Service
public class ScoreTaskTypeServiceImpl implements ScoreTaskTypeService {

    @Resource
    private ScoreTaskTypeMapper scoreTaskTypeMapper;

    /**
     * 查询积分任务类型列表
     * @param scoreTaskType
     * @return
     */
    @Override
    public AjaxResult getScoreTaskTypeList(ScoreTaskType scoreTaskType) {
        List<ScoreTaskType> list = scoreTaskTypeMapper.getScoreTaskTypeList(scoreTaskType);
        return AjaxResult.success(list);
    }

    /**
     * 新增积分任务类型
     * @param scoreTaskType
     * @return
     */
    @Override
    public AjaxResult addScoreTaskType(ScoreTaskType scoreTaskType) {
        //检查任务类型是否存在
        checkTaskTypeExist(scoreTaskType);
        scoreTaskType.setCreateBy(SecurityUtils.getUsername());
        scoreTaskType.setCreateTime(LocalDateTime.now());
        scoreTaskType.setRemark("新增积分任务类型");
        return scoreTaskTypeMapper.addScoreTaskType(scoreTaskType) > 0 ?
                AjaxResult.success("新增积分任务类型成功") : AjaxResult.error("新增积分任务类型失败");
    }

    /**
     * 修改积分任务类型
     * @param scoreTaskType
     * @return
     */
    @Override
    public AjaxResult updateScoreTaskType(ScoreTaskType scoreTaskType) {
        //检查任务类型是否存在
        checkTaskTypeExist(scoreTaskType);
        scoreTaskType.setUpdateBy(SecurityUtils.getUsername());
        scoreTaskType.setUpdateTime(LocalDateTime.now());
        scoreTaskType.setRemark("修改积分任务类型");
        return scoreTaskTypeMapper.updateScoreTaskType(scoreTaskType) > 0 ?
                AjaxResult.success("修改积分任务类型成功") : AjaxResult.error("修改积分任务类型失败");
    }

    /**
     * 批量删除积分任务类型
     * @param typeIds
     * @return
     */
    @Override
    public AjaxResult batchDeleteScoreTaskType(Integer[] typeIds) {
        return scoreTaskTypeMapper.batchDeleteScoreTaskType(typeIds) > 0 ?
                AjaxResult.success("删除积分任务类型成功") : AjaxResult.error("删除积分任务类型失败");
    }

    /**
     * 检查任务类型是否存在
     * @param scoreTaskType
     */
    public void checkTaskTypeExist(ScoreTaskType scoreTaskType){
       ScoreTaskType scoreTaskType1 =  scoreTaskTypeMapper.getScoreTaskType(scoreTaskType);
       if (scoreTaskType1 != null){
           throw new ServiceException(scoreTaskType.getTypeName()+"已经存在");
       }
    }
}
